package com.syni.mdd.sjb.community.base.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.syni.mdd.sjb.common.component.mybatis.community.entity.SjbQywxAdmin;
import com.syni.mdd.sjb.common.component.mybatis.community.entity.SjbQywxCompanyDepart;
import com.syni.mdd.sjb.common.component.mybatis.community.entity.SjbQywxCompanyUser;
import com.syni.mdd.sjb.common.component.mybatis.community.mapper.SjbQywxCompanyUserMapper;
import com.syni.mdd.sjb.common.component.utils.common.utils.ResultMapHelper;
import com.syni.mdd.sjb.common.component.utils.common.utils.StringUtils;
import com.syni.mdd.sjb.community.base.constants.ResultCode;
import com.syni.mdd.sjb.community.base.constants.ResultMsg;
import com.syni.mdd.sjb.community.base.entity.bo.DepartUserListBo;
import com.syni.mdd.sjb.community.base.entity.vo.rp.GetCorpCompanyUserRpVo;
import com.syni.mdd.sjb.community.base.entity.vo.rq.GetCorpCompanyUserVo;
import com.syni.mdd.sjb.community.base.service.SjbQywxAdminService;
import com.syni.mdd.sjb.community.base.service.SjbQywxCompanyDepartService;
import com.syni.mdd.sjb.community.base.service.SjbQywxCompanyUserService;
import com.syni.mdd.sjb.community.base.utils.OAUtils;
import com.syni.mdd.sjb.community.base.utils.QxwxThirdApiUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wangbaitao
 * @version 1.0.0
 * <h>企业微信员工信息表 service impl</h>
 * @Date 2021/2/22
 **/
@Service
@Transactional
@Log4j2
public class SjbQywxCompanyUserServiceImpl extends ServiceImpl<SjbQywxCompanyUserMapper, SjbQywxCompanyUser>
        implements SjbQywxCompanyUserService {
    @Autowired
    SjbQywxCompanyDepartService sjbQywxCompanyDepartService;

    @Autowired
    QxwxThirdApiUtils qxwxThirdApiUtils;

    @Autowired
    SjbQywxCompanyUserMapper sjbQywxCompanyUserMapper;

    @Autowired
    SjbQywxAdminService sjbQywxAdminService;

    @Override
    public void syncCompanyUserData(String corpId, String permanentCode) {
        //找到对应的授权码
        String accessToken = OAUtils.getAccessTokenByPerCode(corpId,permanentCode);
        //获取所有全部部门
        List<SjbQywxCompanyDepart> departments = sjbQywxCompanyDepartService.getCorpDepartData(corpId,accessToken);
        //循环获取部分成员
        if(departments.size() > 0){
            departments.forEach(ds ->{
                List<SjbQywxCompanyUser> sjbQywxCompanyUsers = new ArrayList<>();
                DepartUserListBo departUserListBo = qxwxThirdApiUtils.departmentUserList(accessToken,ds.getDepartId());
                if(departUserListBo.getErrcode() != null && !departUserListBo.getErrcode().equals("0")){
                    //定位到某个页面
                    return;
                }
                //获取当前部分所有成员
                //查询已存在部门
                Map<String,SjbQywxCompanyUser> sjbQywxCompanyUserMap = this.getMapCorpExistUser(corpId);
                for(DepartUserListBo.DepartUserDetail departUserDetail : departUserListBo.getUserlist()){
                    if(!sjbQywxCompanyUserMap.containsKey(departUserDetail.getUserid())){
                        SjbQywxCompanyUser sjbQywxCompanyUser = new SjbQywxCompanyUser();
                        sjbQywxCompanyUser.setCorpid(corpId);
                        sjbQywxCompanyUserMap.put(departUserDetail.getUserid(),sjbQywxCompanyUser);
                    }
                    SjbQywxCompanyUser sjbQywxCompanyUser = sjbQywxCompanyUserMap.get(departUserDetail.getUserid());
                    BeanUtils.copyProperties(departUserDetail,sjbQywxCompanyUser);
                    if(CollectionUtils.isNotEmpty(departUserDetail.getDepartment())){
                        sjbQywxCompanyUser.setDepartment(JSON.toJSONString(departUserDetail.getDepartment()));
                    }
                }
                if(sjbQywxCompanyUserMap.size() > 0){
                    for(Map.Entry<String,SjbQywxCompanyUser> entry : sjbQywxCompanyUserMap.entrySet()){
                        sjbQywxCompanyUsers.add(entry.getValue());
                    }
                    if(CollectionUtils.isNotEmpty(sjbQywxCompanyUsers)){
                        this.saveOrUpdateBatch(sjbQywxCompanyUsers);
                    }
                }
            });
        }
    }

    public Map<String,SjbQywxCompanyUser> getMapCorpExistUser(String corpId){
        Map<String,SjbQywxCompanyUser> sjbQywxCompanyUserMap = new HashMap<>();
        List<SjbQywxCompanyUser> sjbQywxCompanyUsers = getCorpExistUser(corpId);
        if(CollectionUtils.isNotEmpty(sjbQywxCompanyUsers)){
            for(SjbQywxCompanyUser sjbQywxCompanyUser : sjbQywxCompanyUsers){
                sjbQywxCompanyUserMap.put(sjbQywxCompanyUser.getUserid(),sjbQywxCompanyUser);
            }
        }
        return sjbQywxCompanyUserMap;
    }

    public List<SjbQywxCompanyUser> getCorpExistUser(String corpId){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(SjbQywxCompanyUser.CORP_ID,corpId);
        List<SjbQywxCompanyUser> sjbQywxCompanyUsers = sjbQywxCompanyUserMapper.selectList(queryWrapper);
        return sjbQywxCompanyUsers;
    }

    @Override
    public Map<String, Object> getCorpCompanyUser(GetCorpCompanyUserVo corpCompanyUserVo) {
        SjbQywxAdmin sjbQywxAdmin = sjbQywxAdminService.getById(corpCompanyUserVo.getQxwxAdminId());
        if(sjbQywxAdmin == null){
            return ResultMapHelper.result(ResultCode.CODE_PC_NO_LOGIN, ResultMsg.MSG_PC_TOKEN_FAIL);
        }
        //查询当前企业的管理员列表
        List<SjbQywxAdmin> sjbQywxAdmins = sjbQywxAdminService.getByAdminByCorpId(corpCompanyUserVo.getCorpid());
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(SjbQywxCompanyUser.CORP_ID,sjbQywxAdmin.getCorpid());
        queryWrapper.ne(SjbQywxCompanyUser.USERID,sjbQywxAdmin.getUserid());
        if(StringUtils.isNotBlank(corpCompanyUserVo.getSearchText())){
            queryWrapper.like(SjbQywxCompanyUser.NAME,corpCompanyUserVo.getSearchText());
        }
        if(CollectionUtils.isNotEmpty(sjbQywxAdmins)){
            Set<String> userids = sjbQywxAdmins.stream().map(SjbQywxAdmin::getUserid).collect(Collectors.toSet());
            queryWrapper.notIn(SjbQywxAdmin.USERID,userids);
        }
        GetCorpCompanyUserRpVo corpCompanyUserRpVo = new GetCorpCompanyUserRpVo();
        List<SjbQywxCompanyUser> companyUsers = sjbQywxCompanyUserMapper.selectList(queryWrapper);
        if(CollectionUtils.isNotEmpty(companyUsers)){
            for(SjbQywxCompanyUser sjbQywxCompanyUser : companyUsers){
                GetCorpCompanyUserRpVo.CompanyUser data = new GetCorpCompanyUserRpVo.CompanyUser();
                data.setCropUserId(sjbQywxCompanyUser.getId());
                data.setName(sjbQywxCompanyUser.getName());
                data.setAvatar(sjbQywxCompanyUser.getAvatar());
                data.setDepartment(sjbQywxCompanyUser.getDepartment());
                corpCompanyUserRpVo.getCompanyUsers().add(data);
            }
        }
        return ResultMapHelper.success(corpCompanyUserRpVo);
    }

    @Override
    public List<SjbQywxCompanyUser> getByIdIn(List<String> merberIds) {
        if(CollectionUtils.isEmpty(merberIds)){
            return null;
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in(SjbQywxCompanyUser.ID,merberIds);
        List<SjbQywxCompanyUser> sjbQywxCompanyUsers = sjbQywxCompanyUserMapper.selectList(queryWrapper);
        if(CollectionUtils.isNotEmpty(sjbQywxCompanyUsers)){
            return sjbQywxCompanyUsers;
        }
        return null;
    }

    @Override
    public void deleteCompanyUserByCorpId(String corpId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(SjbQywxCompanyUser.CORP_ID,corpId);
        List<SjbQywxCompanyUser> sjbQywxCompanyUsers = sjbQywxCompanyUserMapper.selectList(queryWrapper);
        if(CollectionUtils.isNotEmpty(sjbQywxCompanyUsers)){
            this.removeByIds(sjbQywxCompanyUsers.stream().map(SjbQywxCompanyUser::getId).collect(Collectors.toSet()));
        }
    }

    @Override
    public Integer countCompanyNum(String corpId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(SjbQywxCompanyUser.CORP_ID,corpId);
        return this.count(queryWrapper);
    }
}
